package jxd.myDwr;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.directwebremoting.Container;
import org.directwebremoting.extend.Handler;
import org.directwebremoting.extend.InitializingBean;
import org.directwebremoting.servlet.NotFoundHandler;
import org.directwebremoting.util.Logger;

public class UrlProcessor
  implements Handler, InitializingBean
{
  private String indexHandlerUrl;
  private Map urlMapping = new HashMap();

  private Handler notFoundHandler = new NotFoundHandler();

  private ExceptionHandler exceptionHandler = new ExceptionHandler();

  private static final Logger log = Logger.getLogger(UrlProcessor.class);

  public void afterContainerSetup(Container container)
  {
    Collection beanNames = container.getBeanNames();
    for (Iterator it = beanNames.iterator(); it.hasNext(); )
    {
      String name = (String)it.next();
      if (name.startsWith("url:"))
      {
        Object bean = container.getBean(name);

        if ((bean instanceof Handler))
        {
          this.urlMapping.put(name.substring("url:".length()), bean);
        }
        else
        {
          log.error("Discarding non Handler for " + name);
        }
      }
    }
  }

  public void handle(HttpServletRequest request, HttpServletResponse response)
    throws IOException
  {
    try
    {
      String pathInfo = request.getPathInfo();

      if ((pathInfo == null) || (pathInfo.length() == 0) || (pathInfo.equals("/")))
      {
        response.sendRedirect(request.getContextPath() + request.getServletPath() + this.indexHandlerUrl);
      }
      else
      {
        for (Iterator it = this.urlMapping.entrySet().iterator(); it.hasNext(); )
        {
          Map.Entry entry = (Map.Entry)it.next();
          String url = (String)entry.getKey();

          if (pathInfo.startsWith(url))
          {
            Handler handler = (Handler)entry.getValue();
            handler.handle(request, response);
            return;
          }
        }

        this.notFoundHandler.handle(request, response);
      }
    }
    catch (Exception ex)
    {
      this.exceptionHandler.setException(ex);
      this.exceptionHandler.handle(request, response);
    }
  }

  public void setIndexHandlerUrl(String indexHandlerUrl)
  {
    this.indexHandlerUrl = indexHandlerUrl;
  }
}